package com.user.domain.entity;

import cn.hutool.core.util.RandomUtil;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import com.oss.client.OssClient;
import com.user.domain.repository.UserRepository;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;


/**
 * @author 大忽悠
 * @create 2022/9/15 20:32
 */
@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
public class User {
    /**
     * 用户文件存放的oss目录
     */
    private static final String USER_DIR = "user/";

    private static final String HEAD_IMG = USER_DIR + "headImg/";

    private static final String DEFAULT_HEAD_IMG_DIR = HEAD_IMG + "default/";

    private Integer id;

    private String username;

    private String password;

    private String headImg;

    private String ipAddr;

    private String selfInformation;

    public static Integer loginVerify(String username, String password, UserRepository userRepository) {
        User user = userRepository.getUser(username, password);
        Assert.notNull(user, "用户不存在");
        return user.getId();
    }

    /**
     * 上传用户头像文件到oss,用户没有设置头像,就随机选择一个默认头像
     *  @param ossClient   oss客户端
     * @param prefix
     * @param headImgFile 用户头像字节流
     */
    public void uploadHeadImg(OssClient ossClient, String prefix, MultipartFile headImgFile) throws IOException {
        InputStream headIn = null;
        if (headImgFile == null || headImgFile.isEmpty()) {
            headImg = prefix+choseOneFromDefaultImgs(ossClient);
        } else {
            headIn = headImgFile.getInputStream();
            headImg=HEAD_IMG + System.currentTimeMillis()+".png";
            ossClient.putObject(headImg, headIn);
            headImg=prefix+headImg;
        }
    }

    /**
     * 从默认头像中,随机选择一个作为当前新注册用户的头像
     *
     * @return
     */
    private String choseOneFromDefaultImgs(OssClient ossClient) {
        ObjectListing objectListing = ossClient.listObjects(DEFAULT_HEAD_IMG_DIR);
        int index = RandomUtil.randomInt(objectListing.getObjectSummaries().size());
        S3ObjectSummary objectSummary = objectListing.getObjectSummaries().get(index);
        return objectSummary.getKey();
    }

    /**
     * 对当前用户进行一系列安全检查,例如: 用户名是否重复
     */
    public void safeCheck(UserRepository userRepository) {
        User user=userRepository.getUser(username);
        Assert.isNull(user,"用户名重复");
    }
}
